[Coding013] LeetCode 347

Top K Frequent Elements

Ben 2023/08/03

More coding records

Get the knowledge flowing and circulating! :)

目录

本题收获

 

题目:347. Top K Frequent Elements

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Example 1:

Example 2:

Constraints:

 


代码1(配 · 手绘过程图)

pq_01

代码解读:

这里的测试样例是

注意1: line20的优先权队列的比较规则,是内置的!

复杂度分析

O(n)

代码2(配 · 手绘过程图)

pq_02

代码解读:

这里的测试样例是

注意1: line38的while循环,这个循环是嵌套在for循环中间,执行的逻辑是,优先权队列会随时以k为限制条件,控制队列中的元素始终不大于k。

注意2: line20的优先权队列的比较规则,变了!

复杂度分析

O(n)

 


 

知识点积累 (Java)

  1. HashMap相关操作

  1. 优先权队列的比较器

  2. 优先权队列的相关操作